﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WellDone
{
    public partial class ChangePasswordDialog : ChildWindow
    {
        public ChangePasswordDialog()
        {
            InitializeComponent();
        }

        private async void btnOK_Click(object sender, RoutedEventArgs e)
        {
            // Ensure old password hash matches current password hash
            string strOldPasswordHash = await Globals.db.GetHashValue(pbOld.Password);
            if (strOldPasswordHash != Globals.currentLogin.col_Password)
            {
                MessageBox.Show("Old password does not match.");
                return;
            }
            // Ensure new password and confirmed password are the same
            if (pbNew.Password != pbConfirm.Password)
            {
                MessageBox.Show("New password does not match confirmed password.");
                return;
            }
            // Ensure new password hash is not the same as the old one
            string strNewPasswordHash = await Globals.db.GetHashValue(pbNew.Password);
            if (strNewPasswordHash == strOldPasswordHash)
            {
                MessageBox.Show("Old password is the same as the new password.");
                return;
            }
            // All is well, update the new password
            Globals.currentLogin.col_Password = pbNew.Password;
            Globals.currentLogin.bFilterPassword = true;
            if (await Globals.db.UpdateLoginObject(Globals.currentLogin) == 1)
                MessageBox.Show("Password updated.");
            else
                MessageBox.Show("Error updating password.");

            this.DialogResult = true;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void pbConfirm_KeyDown(object sender, KeyEventArgs e)
        {
            // Call the OK button handlers if "Enter" is pressed
            if (e.Key == Key.Enter) 
                btnOK_Click(sender, e);
        }
    }
}

